import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    DatagramSocket socket = null;
    String severIp;
    int serverPort;
    public UdpEchoClient(String severIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverPort = serverPort;
        this.severIp = severIp;
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner sc = new Scanner(System.in);
        while (true){
            //从客户端读取数据
            System.out.println("->");
            String request = sc.next();
            //将数据发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(severIp), serverPort);
            socket.send(requestPacket);
            //从服务器读取返回的响应
            DatagramPacket respondPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(respondPacket);
            //把响应转化成字符串并打印出来
            String respond = new String(respondPacket.getData(), 0, respondPacket.getLength());
            System.out.println(respond);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.", 9090);
        udpEchoClient.start();
    }
}
